# -*- coding: utf8 -*-
import threading
import MySQLdb
from config.dbconf import db_conf

class ConnectDB:
    instance = {}
    thr = threading.Lock()

    def __init__(self):
        pass

    # 获取数据库连接
    @staticmethod
    def get_con(db_no):
        if (not ConnectDB.instance.has_key(db_no)):  # 如果实例中没有该连接，则创建
            db_config = db_conf[db_no]  # 获取配置文件中连接信息
            ConnectDB.thr.acquire()  # 加锁
            if (not ConnectDB.instance.has_key(db_no)):  # 避免加锁时，实例被创建，再次检验
                ConnectDB.instance[db_no] = MySQLdb.connect(host=db_config["host"], user=db_config["uname"],
                                                            passwd=db_config["pwd"], db=db_config["db_name"],
                                                            port=db_config["port"], charset=db_config["encoding"])
                ConnectDB.instance[db_no].autocommit = True  # 如果你设为false，在commit之前，所有的sql就像一个事务 对数据库伤害较大
                ConnectDB.thr.release()
        return ConnectDB.instance[db_no]

    # 创建新连接
    @staticmethod
    def get_pool_conn(db_no):
        ConnectDB.thr.acquire()  # 加锁
        db_config = db_conf[db_no]  # 获取配置文件中连接信息
        conn = MySQLdb.connect(host=db_config["host"], user=db_config["uname"], passwd=db_config["pwd"],
                               db=db_config["db_name"], port=db_config["port"], charset=db_config["encoding"])
        conn.autocommit = True  # 如果你设为false，在commit之前，所有的sql就像一个事务 对数据库伤害较大
        ConnectDB.thr.release()
        return conn

    @staticmethod
    def delete_con(db_no):
        if (ConnectDB.instance.has_key(db_no)):
            ConnectDB.thr.acquire()
            ConnectDB.instance[db_no].close()
            del (ConnectDB.instance[db_no])
            ConnectDB.thr.release()

    @staticmethod
    def get_encoding(db_no):
        db_config = db_conf[db_no]
        return db_config["encoding"]

    def __del__(self):
        ConnectDB.thr.acquire()
        if (len(ConnectDB.instance)):
            for each in ConnectDB.instance:
                each.close()
            ConnectDB.instance = {}
        ConnectDB.thr.release()
